$(function () {
    queryAjaxCouponList(1);
    $('body').on('click', '#submitFrom,#querySubmit', function () {
        //点击搜索查询从第一页开始查询
        queryAjaxCouponList(1);
    }).on('click',"#newOpen",function(){
        openIntegralCardVoucherAjaxImportExcel()
    });
    function openIntegralCardVoucherAjaxImportExcel(){
        parent.layer.open({
            type:2,
            area: winArea,
            content: baseloaction+" /admin/IntegralCardVoucher/initImportExcels",
            maxmin: true,
            shade: [0.3, '#000'],
            shadeClose: false,
            title: '新建虚拟卡类商品',
            end: function (){
                window.location.href=baseloaction+"/admin/IntegralCardVoucher/virtual/goodList";
            }
        });

    }

    parent.layer.closeAll();
    /*$('body').on("click", "#unlockBatch", function () { //批量停止
        var obj = $("input[name='couponId']:checked");
        var couponIds = obtainIds(obj);//获取勾选ids
        if (!$.isEmptyObject(couponIds)) {
            updateCouponStatusByIds(couponIds, obj, 2);
        }
    }).on('click', '.unlockAndHistory', function () {//单个停止或单个恢复
        var couponIds = $(this).data('id');
        var status = $(this).attr('data-status');
        var obj = $(this);
        if (status == 1) {
            updateCouponStatusByIds(couponIds, obj, 1);
        }
        if (status == 2) {
            updateCouponStatusByIds(couponIds, obj, 2);
        }
    }).on("click", "#historyBatch", function () { //批量恢复
        var obj = $("input[name='couponId']:checked");
        var couponIds = obtainIds(obj);//获取勾选ids
        if (!$.isEmptyObject(couponIds)) {
            updateCouponStatusByIds(couponIds, obj, 1);
        }
    }).on("click", "#deleteBatch", function () {//批量删除
        var obj = $("input[name='couponId']:checked");
        var couponIds = obtainIds(obj);//获取勾选ids
        if (!$.isEmptyObject(couponIds)) {
            icModale(2, "删除后不可恢复，仍然确认删除么？", 3, function () {
                updateCouponStatusByIds(couponIds, obj, 3);
            });
        }
    }).on('click', '.deleteCoupon', function () {//单个删除
        var couponIds = $(this).data('id');
        var obj = $(this);
        icModale(2, "删除后不可恢复，仍然确认删除么？", 3, function () {
            updateCouponStatusByIds(couponIds, obj, 3);
        });
    });*/

    //判断勾选ID是否为空
    function obtainIds(obj) {
        if (obj.size() == 0) {
            icModale(0, "请选择要批量操作的数据");
            return null;
        } else {
            var couponIds = "";
            obj.each(function (index, em) {
                couponIds += em.value + ",";
            });
            couponIds = couponIds.substr(0, couponIds.length - 1);
            return couponIds;
        }
    }
});

/**
 * 获取优惠券列表页面
 * @param pageNo 当前页码
 */
function queryAjaxCouponList(pageNo) {
    var params = $("#search-form").serializeJSON();
    params = JSON.stringify(params);
    var obj = {
        url: baseloaction + '/admin/IntegralCardVoucher/virtual/goodAjaxList',//请求URL
        contextId: 'coupon-list-context',//响应内容页面设置内容ID
        params: params,//请求参数
        pageNo: pageNo,//页码
        pageCall: queryAjaxCouponList, //分页回调加载数据(点击上下页时调用,该方法也在加载页面完成时调用)
        selectAllId: 'select-all-coupon', //全选框ID
        callback: function () {//数据加载完成回调
            $("#totalNum").html("（共"+total+"条数据）");
            $("#couponCount").val(total);
        }
    };
    ajaxGetListData(obj)
}


/**
 * 批量封禁，批量恢复，批量删除
 * @param userIds
 * @param obj
 * @param isavalible
 */
function updateCouponStatusByIds(couponIds, obj, status) {
    $.ajax({
        url: baseloaction + "/admin/op/coupon/updateOpCouponStatus",
        data: {"couponIds":couponIds,"status": status},
        type: "post",
        dataType: "json",
        success: function (result) {
            if (result.success) {
                icModale(0, result.message);
                var couponList = result.entity;
                if(couponList !=null && couponList.length > 0){
                    if(status==3){//删除
                        var couponCount = $("#couponCount").val();
                        var count = couponCount - couponList.length;
                        $("#totalNum").html('（共' + count + '张优惠券）');
                        if (count == 0) {
                            $("#tbodyCoupon").append(
                                ' <td colspan="11" class="text-center">'
                                + '<div class="noDataTipsBox">'
                                + '<p><span class="c-4e fs16">亲，还没有数据~~~</span></p>'
                                + '</div>'
                                + '</td>'
                            );
                        }
                            console.log(obj);
                            $.each(obj,function (index,coupon) {
                                $(coupon).parents("tr").remove();
                            });




                    }else{
                        $.each(couponList,function (index,coupon) {//处理页面显示
                            var context = '';
                            if(coupon.status ==1){
                                context = '<span class="label label-info">进行中</span>';
                            }else if(coupon.status ==0){
                                context = '<span class="label label-info">未开始</span>';
                            }else if(coupon.status ==2){
                                context = '<span class="label label-danger">已停止</span>';
                            }else if(coupon.status ==7){
                                context = '<span class="label label-danger">已结束</span>';
                            }
                            $("#coupon-status-"+coupon.id).html(context);

                            if(status ==2){//停止
                                //如果是停止状态，则把赠送按钮删除
                                $("#selectUser_"+coupon.id).remove();
                                var em = $("#unlockAndHistory_"+coupon.id);
                                em.html('<i class="fa fa-history"></i>');
                                em.data('original-title','恢复');
                                em.attr("data-original-title",'恢复');
                                em.data('status',1);
                                em.attr("data-status",'1');
                            }else if(status ==1){
                                var em = $("#unlockAndHistory_"+coupon.id);
                                em.html('<i class="fa fa-pause"></i>');
                                em.data('original-title','停止');
                                em.attr("data-original-title",'停止');
                                em.data('status',2);
                                em.attr("data-status",'2');
                                var _list = $("#selectUser_"+coupon.id);
                                if(_list ==null || _list.length <=0){
                                    var context = '<a id="selectUser_'+coupon.id+'" data-id="'+coupon.id+'" data-original-title="赠送" data-placement="bottom" data-toggle="tooltip" class="c-master fs14 ml5 selectUser" href="javascript:void (0);"><i class="fa fa-gift"></i></a>';
                                    em.after(context);
                                }
                            }
                        });
                    }
                }


            } else {
                icModale(0, result.message);
            }
        },
        error: function (error) {
            icModale(0, "系统繁忙,请稍后重试");
        }
    })
}

/**
 * 查找用户赠送
 */
var dataId="";
function selectUserCommon() {
    $('body').on('click', '.selectUser', function () {
        selectUser("checkbox","");
        dataId = $(this).data('id');
    })
}



